package com.appointment.config;

import com.appointment.interceptor.JwtInterceptor;
import com.appointment.utils.JacksonObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private JwtInterceptor jwtInterceptor;

    @Value("${jwt.exclude-paths}")
    private String[] excludePaths;


    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 1. 设置消息转化器
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        // 2. 设置消息转化器
        mappingJackson2HttpMessageConverter.setObjectMapper(new JacksonObjectMapper());
        // 3. 将上面的消息转化器对象添加到mvc的消息转化器的列表中
        converters.add(0, mappingJackson2HttpMessageConverter);
    }

    // 设置token
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor)
                // 拦截所有路径
                .addPathPatterns("/**")
                // 除了这些路径
                .excludePathPatterns(excludePaths);
    }

    // 跨域请求
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080", "http://127.0.0.1:8080")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

